package com.zzyl.nursing.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.BiConsumer;

import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;

/**
 * 设备管理Service业务层处理
 * 
 * @author shenkunlin
 * @date 2025-08-03
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /***
     * 查询产品信息
     * @param productKey
     */

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        //1、创建请求参数
        ShowProductRequest request = new ShowProductRequest();
        //2、封装产品ID
        request.withProductId(productKey);

        //3、调用API
        ShowProductResponse response = client.showProduct(request);

        //4、解析结果集
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return Collections.emptyList();
        }
        return serviceCapabilities;
    }



    @Override
    public List<DeviceShadowVo> queryServiceProperties(String iotId) {
        //1、调用华为云IOT，查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);

        //2、查询不到，返回空
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            return Collections.emptyList();
        }

        //3、转换成Vo数据
        //3.1 获取属性集合信息
        JSONObject  jsonObject =JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTimeInfo = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        List<DeviceShadowVo> vos = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            DeviceShadowVo vo = DeviceShadowVo.builder()
                    .functionId(key)
                    .value(value)
                    .eventTime(eventTimeInfo)
                    .build();
            vos.add(vo);
        });
        return vos;
    }

    /****
     * 根据设备ID查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1、查询本地设备
        Device device = getBaseMapper().selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            return null;
        }

        //2、查询IOT平台设备激活时间、状态
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        //获取状态和激活时间
        String status = response.getStatus();
        //国际标准时间 UTC（比国内时间有8个小时时间差->需要将它转成国内标准时间[上海时间]）
        String activeTimeStr = response.getActiveTime();

        // device->DeviceDetailVo
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(status);

        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(activeTime);
        }
        return vo;
    }


    /***
     * 设备注册
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1、设备名称不能重复
        Long deviceNameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName()));
        if(deviceNameCount>=1){
            //抛出异常
            throw new BaseException("当前设备名称已存在！");
        }

        //2、设备唯一标识不能重复
        Long nodeCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId()));
        if(nodeCount>=1){
            //抛出异常
            throw new BaseException("当前设备标识已存在！");
        }

        //3、同一位置不能绑定相同的产品
        Long sameCount = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getBindingLocation()),Device::getBindingLocation, dto.getBindingLocation())
                .eq(ObjectUtil.isNotEmpty(dto.getLocationType()),Device::getLocationType, dto.getLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getPhysicalLocationType()),Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(ObjectUtil.isNotEmpty(dto.getProductKey()),Device::getProductKey, dto.getProductKey())
        );
        if(sameCount>=1){
            //抛出异常
            throw new BaseException("当前位置已存在相同设备！");
        }

        //4、调用华为云IOT平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        AuthInfo authInfobody = new AuthInfo();
        authInfobody
                .withSecret(UUID.randomUUID().toString().replace("-",""));
        body.withAuthInfo(authInfobody);
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        request.withBody(body);

        //调用华为云
        AddDeviceResponse response = client.addDevice(request);
        String deviceId = response.getDeviceId();

        //5、将数据写入到本地  dto->Device
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId); //设备ID
        device.setSecret(authInfobody.getSecret());
        save(device);
    }


    @Override
    public List<ProductVo> getAllProduct() {
        String jsonObj = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if(ObjUtil.isEmpty(jsonObj)){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonObj,ProductVo.class);
    }

    /***
     * 获取所有产品数据，同步到redis
     */
    @Override
    public void syncProductList() {
        //1、调用华为云IOT平台
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        if(CollUtil.isEmpty(products)){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        //2、若有产品列表，则存入到Redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }


    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        device.setCreateTime(DateUtils.getNowDate());
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }


}
